import os
import LConf
import shutil
import sys


def listFile(rootPath):
    '''列出目录下所有文件（绝对地址）
    '''
    paths = os.walk(rootPath)
    resPaths = []
    for root, dirs, files in paths:
        for file in files:
            fPath = os.path.join(root, file)
            fPath = os.path.abspath(fPath)
            resPaths.append(fPath)
    return resPaths


def allSuff(files):
    '''获取所有文件后缀
    '''
    suffSet = set()
    for file in files:
        suff = os.path.splitext(file)[1]
        if suff != '':
            suffSet.add(suff)
    return suffSet


def matchSuffs(files, suffSet):
    '''查找符合后缀的文件路径

    Args:
        files: 待匹配的文件集
        suffSet: 要筛选的后缀集

    Return:
        筛选后的文件集
    '''
    matched = []
    for file in files:
        if inSuffSet(file, suffSet):
            matched.append(file)
    return matched


def inSuffSet(filePath, suffSet):
    '''判断文件是否为某些后缀
    Args:
        filePath: 文件路径
        suffSet: 要筛选的后缀集

    Return:
        成功与否
    '''
    suff = os.path.splitext(filePath)[1]
    suff = suff.strip('.')
    if suff in suffSet:
        return True
    else:
        return False


def backFiles(files, path, backPath):
    '''文件备份（拷贝）

    Args:
        files: 带拷贝的文件数组
        path: 原目录
        backPath: 拷贝目录
    '''
    for file in files:
        new = file.replace(path, backPath)
        p = os.path.dirname(new)
        os.path.exists(p) or os.makedirs(p)
        shutil.copyfile(file, new)


if __name__ == '__main__':

    iniPath = 'conf.ini'
    # 读取命令行参数
    if len(sys.argv[1:]) >= 1:
        iniPath = sys.argv[1]
    # 读取配置文件
    conf = LConf.iniConf('conf.ini')
    needSuffs = conf['suff'].split(',')
    # 列出目录下所有文件
    files = listFile(conf['path'])
    if len(files) == 0:
        input("is empty or not exist your path")
        exit()
    # 根据配置后缀匹配文件
    matchedFiles = matchSuffs(files, needSuffs)
    # 备份文件
    backFiles(matchedFiles, conf['path'], conf['bakPath'])
    msg = "is Ok!! you files in " + conf['bakPath'] + "\nPress any key to exit"
    input(msg)
